<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" :form="queryForm">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="角色名称">
              <a-input
                placeholder="角色名称"
                :maxLength="20"
                v-decorator="['name', { initialValue: this.queryParam.name }]"
              />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="角色标识">
              <a-input
                placeholder="角色名称"
                :maxLength="25"
                v-decorator="['code', { initialValue: this.queryParam.code }]"
              />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="是否有效">
              <a-select placeholder="请选择" v-decorator="['enabled', { initialValue: this.queryParam.enabled }]">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="true">有效</a-select-option>
                <a-select-option value="false">无效</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="this.search">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetForm">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" icon="plus" v-action:sys:role:add @click="add">新建</a-button>
      <a-button
        type="primary"
        :disabled="selectedRowKeys.length != 1"
        icon="edit"
        v-action:sys:role:update
        @click="edit()"
        >编辑</a-button
      >
      <a-button
        type="danger"
        :disabled="selectedRowKeys.length == 0"
        icon="delete"
        v-action:sys:role:delete
        @click="del"
        >删除</a-button
      >
    </div>
    <a-spin :spinning="loading">
      <s-table
        ref="table"
        size="middle"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        bordered
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      >
        <span slot="action" slot-scope="text, record">
          <a href="javascript:;" @click="view(record.id)">查看</a>
          <span v-action:sys:role:update>
            <a-divider type="vertical" />
            <a href="javascript:;" @click="edit(record.id)">编辑</a>
          </span>
          <span v-action:sys:role:delete>
            <a-divider type="vertical" />
            <a href="javascript:;" @click="deletes(record.id)">删除</a>
          </span>
        </span>

        <span slot="roleEnabled" slot-scope="enabled">
          <a-tag :color="enabled ? 'green' : 'red'">
            {{ enabled ? '有效' : '无效' }}
          </a-tag>
        </span>
      </s-table>
    </a-spin>
    <!--新增/修改/查看弹出层-->
    <a-modal
      :title="formDisabled ? '查看' : this.$isNull(this.formData) || this.$isNull(this.formData.id) ? '新增' : '更新'"
      :width="960"
      :visible="visible"
      :centered="true"
      :confirmLoading="loading"
      :maskClosable="false"
      :destroyOnClose="true"
      :keyboard="true"
      @cancel="visibleModal()"
    >
      <a-spin :spinning="loading">
        <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
          <a-row :gutter="24" style="display:none;">
            <a-col :span="24">
              <a-form-item label="主键">
                <a-input v-decorator="['id', { rules: [{ required: false }], initialValue: this.formData.id }]" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="角色名称">
                <a-input
                  :disabled="formDisabled"
                  :maxLength="20"
                  v-decorator="[
                    'name',
                    {
                      rules: [{ required: true, message: '请输入角色名称' }],
                      initialValue: this.formData.name
                    }
                  ]"
                  placeholder="请输入角色名称"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="角色标识">
                <a-input
                  :maxLength="25"
                  :disabled="formDisabled"
                  v-decorator="[
                    'code',
                    { rules: [{ required: true, message: '请输入角色标识' }], initialValue: this.formData.code }
                  ]"
                  placeholder="请输入角色标识"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="角色权限">
                <tree
                  v-decorator="[
                    'menuIds',
                    {
                      rules: [{ required: true, message: '请选择菜单' }],
                      initialValue: this.formData.menuIds
                    }
                  ]"
                  :disabled="formDisabled"
                  checkable
                  :checkStrictly="true"
                  :defaultExpandAll="formDisabled"
                  :defaultExpandedKeys="!this.$isNull(this.formData.menuIds) ? this.formData.menuIds.split(',') : []"
                  :defaultCheckedKeys="!this.$isNull(this.formData.menuIds) ? this.formData.menuIds.split(',') : []"
                  :treeData="menuTree"
                  @check="this.menuCheck"
                >
                </tree>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="是否有效">
                <a-switch
                  :disabled="formDisabled"
                  checkedChildren="有效"
                  unCheckedChildren="无效"
                  v-decorator="[
                    'enabled',
                    {
                      valuePropName: 'checked',
                      rules: [{ required: true, message: '请选择是否有效' }],
                      initialValue: this.$isNull(this.formData.id) ? true : this.formData.enabled
                    }
                  ]"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="描述">
                <a-textarea
                  allow-clear
                  :disabled="formDisabled"
                  :autoSize="{ minRows: 5, maxRows: 6 }"
                  :maxLength="150"
                  placeholder="描述"
                  v-decorator="[
                    'description',
                    { rules: [{ required: false }], initialValue: this.formData.description }
                  ]"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
      <template slot="footer">
        <a-button key="back" @click="visibleModal()">
          返回
        </a-button>
        <a-button key="submit" type="primary" v-show="!formDisabled" :loading="loading" @click="save">
          保存
        </a-button>
      </template>
    </a-modal>
  </a-card>
</template>

<script>
import { Tree } from 'ant-design-vue'
import { STable } from '@/components'
import { list, del, add, get, update } from '@/api/system/role/role'
import { tree } from '@/api/system/menu/menu'
export default {
  name: 'Role',
  components: {
    STable,
    Tree
  },
  data() {
    return {
      // 高级搜索 展开/关闭
      advanced: true,
      // 新增/修改用户弹出层
      visible: false,
      // 禁用表单所有元素
      formDisabled: false,
      // 用户 新增/编辑表单
      formData: {},
      // 数据表单
      form: this.$form.createForm(this),
      // 查询表单
      queryForm: this.$form.createForm(this),
      // 新增/编辑 弹出层加载
      loading: false,
      // 查询参数
      queryParam: {
        pageIndex: 1,
        pageSize: 10,
        name: '',
        code: '',
        enabled: null
      },
      // 列表字段表头
      columns: [
        {
          title: '角色名称',
          dataIndex: 'name',
          width: '12%',
          ellipsis: true
        },
        {
          title: '角色标识',
          dataIndex: 'code',
          width: '15%'
        },
        {
          title: '是否有效',
          width: '8%',
          dataIndex: 'enabled',
          align: 'center',
          scopedSlots: { customRender: 'roleEnabled' }
        },
        {
          title: '描述',
          width: '20%',
          dataIndex: 'description',
          ellipsis: true
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: '16%',
          ellipsis: true
        },
        {
          title: '更新时间',
          dataIndex: 'updateTime',
          width: '16%',
          ellipsis: true
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          width: '15%',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => this.list(parameter),
      selectedRowKeys: [],
      selectedRows: [],
      // 角色拥有的菜单权限
      menuTree: []
    }
  },
  methods: {
    // 重置表单
    resetForm() {
      this.queryForm.resetFields()
      this.search()
    },
    // 查询数据
    search() {
      this.$refs.table.refresh(true)
    },
    // 列表查询数据
    list(params) {
      let queryParam = {}
      this.queryForm.validateFields((errors, values) => {
        queryParam = {
          ...this.queryParam,
          ...params,
          ...values
        }
      })
      return list(queryParam)
        .then(res => {
          return res.data
        })
        .catch(err => {
          console.log(err)
        })
        .finally(() => {
          this.onSelectChange([], [])
        })
    },
    // 选择数据
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    // 新增
    add() {
      this.visibleModal()
    },
    // 编辑
    edit(id) {
      this.visibleModal(this.$isNull(id) ? this.selectedRowKeys[0] : id, null, false)
    },
    // 保存表单
    save(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.loading = true
          let promise = null
          if (!this.$isNull(values.id)) {
            promise = update(values)
          } else {
            promise = add(values)
          }
          promise
            .then(res => {
              if (res.code !== 200) {
                this.$message.error(res.msg)
              } else {
                this.visibleModal(null, res.msg, false)
              }
            })
            .catch(err => {
              console.log(err)
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    // 确认删除
    del() {
      const _this = this
      this.$confirm({
        centered: true,
        content: h => (
          <div>
            确认删除当前选中的 <b style="color:red;">{this.selectedRowKeys.length}</b> 条数据?
          </div>
        ),
        onOk() {
          _this.deletes(_this.selectedRowKeys.join(','))
        },
        onCancel() {
          _this.search()
        },
        class: 'deleteConfirm'
      })
    },
    // 删除数据
    deletes(ids) {
      del(ids)
        .then(res => {
          if (res.code !== 200) {
            this.$message.error(res.msg)
          } else {
            this.onSelectChange([], [])
          }
        })
        .catch(err => {
          console.log(err)
        })
        .finally(() => {
          this.search()
        })
    },
    // 查看详情
    view(id) {
      this.visibleModal(id, null, true)
    },
    // 关闭新增/编辑/查看弹出层
    visibleModal(id, message, formDisabled) {
      if (this.visible) {
        this.search()
      } else {
        this.loading = true
        this.formDisabled = this.$isNull(formDisabled) ? false : formDisabled
        this.formData = {}
        tree().then(res => {
          if (res.code !== 200) {
            this.$message.error(res.msg)
            return
          }
          this.menuTree = res.data
        })
      }

      if (this.$isNull(id)) {
        this.loading = false
        this.visible = !this.visible
      } else {
        get(id)
          .then(res => {
            if (res.code !== 200) {
              this.$message.error(res.msg)
              this.search()
              return
            }
            this.visible = !this.visible
            this.formData = this.$isNull(res.data) ? {} : res.data
            if (!this.$isNull(message)) {
              this.$message.success(message)
            }
          })
          .catch(err => {
            console.log(err)
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    // 选择菜单
    menuCheck(checkedKeys, info) {
      this.form.setFieldsValue({
        menuIds: checkedKeys.checked.join(',')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  margin-bottom: 54px;
}

.fold {
  width: calc(100% - 216px);
  display: inline-block;
}

.operator {
  margin-bottom: 18px;
}

@media screen and (max-width: 900px) {
  .fold {
    width: 100%;
  }
}
.ant-calendar-picker {
  width: 358px !important;
}
</style>
